package org.stone.project.tx.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.stone.project.tx.prop.TxProp;
import org.stone.project.tx.service.MsgTypeHandlerAdapter;

import javax.annotation.PostConstruct;

@Slf4j
@Configuration
public class NettyServer {
    @Autowired
    private TxProp txProp;

    @Autowired
    private MsgTypeHandlerAdapter msgTypeHandlerAdapter;


    @PostConstruct
    public void initNettyServer(){
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup work = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss,work)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>(){
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new HttpServerCodec())
                                .addLast(new ChunkedWriteHandler())
                                .addLast(new HttpObjectAggregator(1024*64))
                                .addLast(new WebSocketServerProtocolHandler("/chat"))
                                .addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>(){
                                    @Override
                                    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                                        super.handlerAdded(ctx);
                                        CtxHolderProxy.linkRemoveExist(ctx);
                                        log.info("ip为{}连接",ctx.channel().remoteAddress().toString());
                                    }

                                    @Override
                                    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
                                        super.handlerRemoved(ctx);
                                        CtxHolderProxy.unLinkRemoveExist(ctx);
                                        log.info("ip为{}服务断开连接",ctx.channel().remoteAddress().toString());
                                    }

                                    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
                                        JSONObject req = JSONUtil.parseObj(msg.text());
                                        Integer type = (Integer) req.get("type");
                                        String token = (String) req.get("token");
                                        JSONObject data = (JSONObject) req.getJSONObject("data");
                                        msgTypeHandlerAdapter.handleMsgType(token,type,data,channelHandlerContext);
                                    }
                                })
                        ;
                    }
                })
                .option(ChannelOption.SO_BACKLOG,1024)
                .option(ChannelOption.SO_KEEPALIVE,true);

        ChannelFuture sync = null;
        try {
            sync = serverBootstrap.bind(txProp.getPort())
                    .sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if (null == sync || !sync.isSuccess()){
                boss.shutdownGracefully();
                work.shutdownGracefully();
            }else {
                log.info("netty服务启动成功");
            }
        }
    }
}
